﻿$(document).ready(function() {
    var basehUrl = "http://search.twitter.com/search.json";
    $('#searchButton').click(function() {
        $("#tweetMainContainer").empty();
        $("#getMoreTweetsButton").hide();
        GetTweets($('#searchText').val(), 10);
    });
    $("#getMoreTweetsButton").hide();
});

function GetTweets(query, count) {
    var searchUrl = "http://search.twitter.com/search.json?q=" + query + "&rpp=" + count + "&lang=en&callback=?";
    
    $.getJSON(searchUrl, function(data) {
        ApplyTwitterTemplate(data);
    });
}

function GetMoreTweets(query) {
    var searchUrl = "http://search.twitter.com/search.json" + query + "&callback=?";
    $.getJSON(searchUrl, function(data) {
        ApplyTwitterTemplate(data);
    });
}

function ApplyTwitterTemplate(data) {
    $tweetSubContainer = $("#tweetSubContainer").clone();
    $tweetSubContainer.hide();
    $tweetSubContainer.setTemplateURL('Twitter.htm',
                                 null, { filter_data: false });
    $tweetSubContainer.processTemplate(data);
    $("#tweetMainContainer").append($tweetSubContainer);

    //show get more button and set next page url
    $("#getMoreTweetsButton").unbind('click', null);
    $("#getMoreTweetsButton").click(function() {
        GetMoreTweets(data.next_page);
    }).show();

    $tweetSubContainer.fadeIn("slow");
}